package cn.youwan.market.adapter;

import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import cn.youwan.market.MyApplication;
import cn.youwan.market.R;
import cn.youwan.market.database.MyDao;
import cn.youwan.market.download.AppDownloadService;
import cn.youwan.market.entity.DownFile;
import cn.youwan.market.entity.PromotionListbean.Appbean;
import cn.youwan.market.utils.BitmapManager;
import cn.youwan.market.utils.Const;
import cn.youwan.market.utils.Utils;

public class TuijianAdapter extends BaseAdapter {

	private Context mContext;
	private List<Appbean> mDataSource;
	private Appbean bean;
	//	private TextView animText;
	//	private ListView listView;
	//	private ImageView tagImg;
	//	private ImageView appIconImg;
	//	private TextView appNameTxt;
	//	private TextView appSizeTxt;
	//	private TextView appPlayerTxt;
	//	private TextView appDownTxt;
	//	private TextView appDesTxt;
	//	private TextView installTxt;
	private BitmapManager bmpManager;
	private List<DownFile> downFils;


	public TuijianAdapter(Context context, List<Appbean> data,ListView listView){
		this.mContext = context;
		this.mDataSource = data;
		//this.listView = listView;
		bmpManager=new BitmapManager();
		if (downFils == null) {
			MyDao dao = new MyDao(context);
			downFils = dao.queryAllDownApk();
		}
	}

	@Override
	public int getCount() {
		return mDataSource.size();
	}

	@Override
	public Object getItem(int position) {
		return mDataSource.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {

		bean = mDataSource.get(position);

		final HoldView hold;
		if (convertView == null) {
			hold = new HoldView();
			convertView = LayoutInflater.from(mContext).inflate(
					R.layout.tuijian_list_item, null);
			hold.tagImg = (ImageView) convertView.findViewById(R.id.tuijian_tagImg);
			hold.appIconImg = (ImageView) convertView.findViewById(R.id.tuijian_icon);
			hold.appNameTxt = (TextView) convertView.findViewById(R.id.tuijian_appName);
			hold.appSizeTxt = (TextView) convertView.findViewById(R.id.tuijian_appSize);
			hold.appPlayerTxt = (TextView) convertView.findViewById(R.id.tuijian_player);
			hold.appDownTxt = (TextView) convertView.findViewById(R.id.tuijian_downNumber);
			hold.appDesTxt = (TextView) convertView.findViewById(R.id.tuijian_des);
			hold.installTxt = (TextView) convertView.findViewById(R.id.tuijian_install);
			convertView.setTag(hold);
			hold.installTxt.setTag(position);
		}else {
			hold = (HoldView) convertView.getTag();
		}

		hold.appNameTxt.setText(bean.getAppName());
		hold.appSizeTxt.setText(bean.getFileSize());
		hold.appPlayerTxt.setText((int)Integer.parseInt(bean.getDownloadCount())/8 + (int)(Math.random()*1000)+"人");
		hold.appDownTxt.setText(bean.getDownloadCount()+"人");
		hold.appDesTxt.setText(bean.getIntroduce());
		hold.installTxt.setTag(position);
		bmpManager.loadBitmap(bean.getAppIcon(), hold.appIconImg);


		if (bean.getDownState() == -1) {
			getDownState(bean);
		}
		setDownBtn(bean.getDownState(), hold.installTxt);
		hold.installTxt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				int pos=(Integer) v.getTag();
				bean=mDataSource.get(pos);
					switch (bean.getDownState()) {
					// 下载
					case 0:
						tipNotWifi(2, bean, hold.installTxt);
						break;
						// 升级 也是下载
					case 1:
						tipNotWifi(2, bean, hold.installTxt);
						break;
						// 下载中
					case 2:
						pause(5, bean, hold.installTxt);
						break;
						// 安装
					case 3:
						Utils.installApp(mContext, bean.getPkg());
						break;
						// 打开
					case 4:
						Utils.openApp(mContext, bean.getPkg());
						break;
						// 暂停 也是下载
					case 5:
						tipNotWifi(2, bean, hold.installTxt);// 继续下载
						break;
					}
				
			}
		});


		//hold.installTxt.setTag(position);
		//hold.installTxt.setOnClickListener(mDownloadListener);

		return convertView;
	}

	private void setDownBtn(int downState, TextView downBtn) {
		switch (downState) {
		case 0:
			downBtn.setText("下载");
			break;
		case 1:
			downBtn.setText("升级");
			break;
		case 2:
			if (downBtn != null) {
				downBtn.setText("下载中");
			}
			break;
		case 3:
			downBtn.setText("安装");
			break;
		case 4:
			downBtn.setText("打开");
			break;
		case 5:// 暂停
			downBtn.setText("继续");
			break;
		}
	}

	class HoldView {
		ImageView tagImg;
		ImageView appIconImg;
		TextView appNameTxt;
		TextView appSizeTxt;
		TextView appPlayerTxt;
		TextView appDownTxt;
		TextView appDesTxt;
		TextView installTxt;
	}

	// 判断是否是非wifi环境，并且判断是否需要弹出框提示
	private void tipNotWifi(final int state, final Appbean bean,
			final TextView button) {
		if (!Utils.hasNetwork(mContext)) {
			Toast.makeText(mContext, "没有网络", Toast.LENGTH_SHORT).show();
			return;
		}

		if (Utils.isWifi(mContext)) {
			gotoDownload(state, bean, button);
			return;
		}
		if (!Const.DownLoadTip) {
			gotoDownload(state, bean, button);
			return;
		}
		new AlertDialog.Builder(mContext).setTitle("确认")
		.setMessage("当前不是wifi环境，确定要下载吗？")
		.setPositiveButton("是", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				Const.DownLoadTip = false;
				gotoDownload(state, bean, button);
			}
		})
		.setNegativeButton("否", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				saveProgressApp(bean);
			}
		}).show();
	}

	private void gotoDownload(int state, Appbean bean, TextView button) {
		if (!Utils.hasSDCard()) {
			Toast.makeText(mContext, "没有SD卡", Toast.LENGTH_SHORT).show();
			return;
		}
		if (!Utils.hasNetwork(mContext)) {
			Toast.makeText(mContext, "没有网络", Toast.LENGTH_SHORT).show();
			return;
		}

		bean.setDownState(state);
		Intent intent = new Intent();
		intent.setAction(Const.START_DOWNLOAD_ACTION);
		Bundle bundle = new Bundle();
		bundle.putSerializable("bean", bean);
		intent.putExtras(bundle);
		mContext.startService(intent);
		setDownBtn(state, button);
	}

	private void pause(int state, Appbean bean, TextView button) {
		bean.setDownState(state);
		Intent intent = new Intent();
		intent.setAction(Const.PAUSE_DOWNLOAD_ACTION);
		intent.putExtra("pkg", bean.getPkg());
		mContext.startService(intent);
		setDownBtn(state, button);
	}

	// 暂停保存到数据库 只保存一次
	private void saveProgressApp(Appbean bean) {
		MyDao dao = new MyDao(mContext);
		DownFile file = new DownFile();
		file.appId = bean.getId();
		file.company = bean.getAppCompany();
		file.name = bean.getAppName();
		file.rate = String.valueOf(bean.getRate());
		file.icon = bean.getAppIcon();
		file.fileSize = bean.getAppSize();
		file.url = bean.getUrl();
		file.pkg = bean.getPkg();
		file.state = 0;
		dao.insert(file);
	}

	// 判断下载状态
	private void getDownState(Appbean bean) {
		String pkg = bean.getPkg();
		int downState = 0;
		String sa=MyApplication.instance.sha;
		Log.i("sha", sa);
		// 判断是否为已安装
		if (MyApplication.instance.getInstallApps()
				.containsKey(pkg)) {
			if (MyApplication.instance.getInstallApps()
					.get(pkg).versionCode < bean.getVersion()) {
				downState = 1;
			} else {
				downState = 4;
			}
			bean.setDownState(downState);
			return;
		}
		// 判断是否在下载中
		if (AppDownloadService.getDownloadingApps() != null
				&& AppDownloadService.getDownloadingApps().containsKey(pkg)) {
			if (AppDownloadService.getDownloadingApps().get(pkg).getDownState() == 2) {
				downState = 2;
			} else if (AppDownloadService.getDownloadingApps().get(pkg)
					.getDownState() == 5) {
				downState = 5;
			} else if (AppDownloadService.getDownloadingApps().get(pkg)
					.getDownState() == 3) {
				downState = 3;
			}
			bean.setDownState(downState);
			return;
		}
		DownFile file = getDownFile(pkg);
		if (file != null) {
			if (file.state == 0) {
				downState = 5;
			} else if (file.state == 1) {
				downState = 3;
			}
			bean.setDownState(downState);
			return;
		}
		bean.setDownState(downState);
	}


	private DownFile getDownFile(String pkg) {
		for (DownFile file : downFils) {
			if (file.pkg.equals(pkg)) {
				return file;
			}
		}
		return null;
	}

	//		private View.OnClickListener mDownloadListener = new OnClickListener() {
	//
	//			@Override
	//			public void onClick(View v) {
	//				int[] location = new int[2];
	//				v.getLocationOnScreen(location);
	//				int position = (Integer) v.getTag();
	//				
	//			}
	//
	//		};

}
